from alipay import AliPay
from django.conf import settings
from rest_framework.response import Response
from rest_framework.views import APIView

from orders.models import OrderInfo


class AlipayUrlView(APIView):
    def get(self, request, order_id):
        try:
            order = OrderInfo.objects.get(pk=order_id)
        except:
            raise Exception('订单号无效')

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=settings.APP_PRIVATE_KEY,
            alipay_public_key_path=settings.ALIPAY_PUBLICT_KEY,
            debug=settings.ALIPAY_DEBUG
        )

        order_string = alipay.api_alipay_trade_page_pay(
            subject=settings.ALIPAY_SUBJECT,
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL
        )

        return Response({'alipay_url': settings.ALIPAY_GATE_URL + order_string})
